package com.jsu.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jsu.bean.CurrentMax;
import com.jsu.bean.LostMessage;
import com.jsu.bean.Matched;
import com.jsu.dao.FoundMessageMapper;
import com.jsu.dao.LostMessageMapper;
import com.jsu.dao.MatchedMapper;
import com.jsu.face.Face_Operate;
import com.jsu.face.FindFaceSetOutid;
import com.jsu.face.LostFaceSetOutid;
import com.sun.org.apache.bcel.internal.generic.NEW;
@Component
public class LostMatchToFound {
	
	@Autowired
	CurrentMax currentMax;
	@Autowired
	LostMessageMapper lostMessageMapper;
	@Autowired
	FoundMessageMapper foundMessageMapper;
	@Autowired
	Face_Operate face_Operate;
	@Autowired
	MatchedMapper matchedMapper;
	@Autowired
	Matched matched;
	
	String lostFaceSetID=LostFaceSetOutid.getInstance().getLostFaceSetID();
	String findFaceSetID=FindFaceSetOutid.getInstance().getFindFaceSetID();
	String photoBasic;
	
	List<Matched> list = new ArrayList<Matched>();
	
	public void setTar(CurrentMax currentMax,String photoBasic){
		this.currentMax.setCurrentId(currentMax.getCurrentId());
		this.currentMax.setMaxId(currentMax.getMaxId());
		this.photoBasic=photoBasic;
	}

	
	public void run() {
		int currentId = currentMax.getCurrentId();
		int maxId = currentMax.getMaxId();
		for(int i=currentId+1;i<=maxId;i++){
			LostMessage lostMessage = lostMessageMapper.selectByPrimaryKey(i);
			if(lostMessage!=null){
				Integer lostMessageId = lostMessage.getLostmessageId();
				String faceToken = lostMessage.getFacetoken();
				String photoPath = lostMessage.getPhotopath();
				if(faceToken!=null&&(!faceToken.trim().equals(""))&&photoPath!=null&&(!photoPath.trim().equals(""))){
					try {
						byte[] photo = face_Operate.toByteArray(photoBasic+photoPath);
						Map<String,String> faceMap = face_Operate.search_faceset(photo, faceToken, findFaceSetID);
						Iterator<Map.Entry<String, String>> it = faceMap.entrySet().iterator();
						while(it.hasNext()){
							Map.Entry<String, String> faceEntry = it.next();
					    	Integer foundMessageId = foundMessageMapper.selectIdByToken(faceEntry.getValue());
					    	Matched matched = new Matched();
					    	matched.setFoundmessageId(foundMessageId);
					    	matched.setLostmessageId(lostMessageId);
					    	matched.setType(0);
					    	matched.setSimilarity(Float.parseFloat(faceEntry.getKey()));
					    	list.add(matched);
					    }
						matchedMapper.insertBatch(list);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		
	}

	
}
